package hy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import hy.entity.Users;
import hy.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyUserService implements UserDetailsService{
    @Autowired
    PasswordEncoder pe;
    @Autowired
    UserMapper um;
    @Override//参数是controller传来的用户名
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
       //调用userMapper方法，根据用户名查询数据库
        QueryWrapper<Users> q=new QueryWrapper<>();
        //where username=?
        q.eq("username",name);
        Users u=um.selectOne(q);//从数据库中查到用户名a1及密码123
        System.out.println(pe.encode(u.getPassword()));
        if(u==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //添加两个角色,可从数据库中查出
        List<GrantedAuthority>list= AuthorityUtils.commaSeparatedStringToAuthorityList("manager,admin,ROLE_sale");
        //前端传来的密码加密后得到密文p1,数据库中密码进行加密得到p2,判断p1是否等于p2
        //return new User("a1",pe.encode("123"),list);
        return new User(u.getUsername(),pe.encode(u.getPassword()),list);
    }
    //create table users(id int primary key auto_increment,username char(32),password char(32),role char(32));
    //insert into users values(1,'a1','123','manager,admin');
}
